<?php

namespace app\command;

use support\Log;
use support\Redis;
use think\facade\Db;
use PhpAmqpLib\Wire\AMQPTable;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use App\service\order\BoxOrderServices;


class BoxNotifyTest extends Command
{
    protected static $defaultName = 'box:notify:test';
    protected static $defaultDescription = 'box notify test';

    /**
     * @return void
     */
    protected function configure()
    {
        $this->addArgument('name', InputArgument::OPTIONAL, 'Name description');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
//        $name = $input->getArgument('name');
//        $output->writeln('Hello box:notify:test');

        $v_host = env('RABBITMQ_VHOST');
        $exc_name = 'delay_exc_box_notify_test';
        $routing_key = 'delay_box_notify_test';
        $queue_name = 'delay_queue_box_notify_test';
        $connection = new AMQPStreamConnection('localhost', 5672, env('RABBITMQ_USER'), env('RABBITMQ_PWD'), $v_host);
        $channel = $connection->channel();
        $channel->exchange_declare($exc_name, 'x-delayed-message', false, true, false);
        # 后加
        $args = new AMQPTable(['x-delayed-type' => 'direct']);
        $channel->queue_declare($queue_name, false, true, false, false, false, $args);

        $channel->queue_bind($queue_name, $exc_name, $routing_key);

        $callback = function ($msg) use ($output) {
            //$output->writeln($msg->body);

            $order_id = $msg->body;

            $boxOrderServices = new BoxOrderServices();

            $res = $boxOrderServices->boxPayNotifyTest((string)$order_id);

            if (!$res) {
                $res = $boxOrderServices->boxPayNotifyTest((string)$order_id);
                if (!$res) {
                    $boxOrderServices->boxPayNotifyTest((string)$order_id);
                }
            }

            $msg->ack();
        };
        $channel->basic_qos(null, 1, null);
        $channel->basic_consume($queue_name, '', false, false, false, false, $callback);

        while ($channel->is_open()) {
            $channel->wait();
        }

        return self::SUCCESS;
    }

}
